#include <zneo.h>
#include "system.h"
#include "clock.h"
#include "LEDs.h"

char str[MAX_STRING_LENGTH];
char* strPtr;
short refreshCounter;
int scrollCounter;
extern int scrollRate;

void led_interrupt(void);

void initialize_led_timer(void) {
	int reloadValue;

	strPtr = str;
	refreshCounter = 0;
	scrollCounter = 0;

	// Timer0 Configurations

	// Disable the timer
	T0CTL1 |= 0x7F;

	// Timer Control settings
	// INCAP = 0 - Previous timer interrupt is not a result of a timer input capture even
	// PWMD = 000 - No delay
	// CASCADE = 0 - The timer is not cascaded
	// TICONFIG = 00 - Timer interrupt occurs on reload
	// TMODE = 0001 - Continuous mode
	// PRES = 001 - Divide by 2
	// TPOL = 1 - Output bit
	// TEN = 0 - Timer disabled
	T0CTL0 = 0x00; // 0 00 0 000 0 (TMODE[3], TICONFIG, CASCADE, PWMD, INCAP)
	T0CTL1 = 0x49; // 0 1 001 001 (TEN, TPOL, PRES, TMODE[2:0])
	T0L = 0x01;
	T0H = 0x00;
	// Set the clock speed to 1 ms
	reloadValue = 1 * CLOCK_SPEED / 2 / 1000;
	T0R = reloadValue;

	// Enable the interrupt
	IRQ0ENL |= 0x20;
	IRQ0ENH |= 0x20;

	// Enable the timer
	T0CTL1 |= 0x80;

	// Associate the ISR
	SET_VECTOR(TIMER0, led_interrupt);
}

// Interrupt Service Routines

#pragma interrupt
void led_interrupt(void) {

	// The code to handle the LED scanning
	if (refreshCounter == REFRESH_RATE) {
		scan_led();
		refreshCounter = 0;
	} else {
		refreshCounter++;
	}

	// The code to handle the character scrolling
	if (scrollCounter >= scrollRate) {
		scroll_led();
		scrollCounter = 0;
	} else {
		scrollCounter++;
	}
}